package com.zyf.chapter02.behavior.observer.async;

import com.zyf.chapter02.behavior.observer.p2p.UserService;
import com.zyf.chapter02.behavior.observer.p2p.refactor.RegObserver;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * 第二种异步非阻塞观察者模式的实现方式
 * <p>
 * 优点：利用线程池解决了第一种实现方式的问题。<br />
 * 缺点：线程池、异步执行逻辑都耦合在了 register() 函数中，增加了这部分业务代码的维护成本。
 * @author yifeng
 */
public class UserController {
    private UserService userService;
    private List<RegObserver> regObserverList = new ArrayList();
    private Executor executor;

    public UserController(Executor executor) {
        this.executor = executor;
    }

    public void setRegObservers(List<RegObserver> observers) {
        regObserverList.addAll(observers);
    }

    public Long register(String telephone, String password) {
        // 省略输入参数的校验代码
        // 省略 userService.register() 异常的 try-catch代码
        long userId = userService.register(telephone, password);
        for (RegObserver regObserver : regObserverList) {
            executor.execute(() -> regObserver.handleRegSuccess(userId));
        }
        return userId;
    }
}
